<?php                                                                                                                                                                                                                          

/*

Query the database for point strings for polygons within given extents

*/

$path = dirname(dirname(__FILE__));
require($path.'/lib/crt.php');

$crt = new CRT();
$crt->init();

$zoom = $_REQUEST['zoom'];
$minX = Clean::float($_REQUEST['minX']);
$maxX = Clean::float($_REQUEST['maxX']);
$minY = Clean::float($_REQUEST['minY']);
$maxY = Clean::float($_REQUEST['maxY']);
$layer = Clean::string($_REQUEST['layer']);


require_once(PLUGIN_PATH.'/lib/polyline-encoder.php');
//require_once(PLUGIN_PATH.'/lib/markets.php');

$db = DBs::getGISDB();


// HACK for now, tables will be renamed i'm assuming
if($layer=='census') {
	$tableName = BLOCKS_TBL;
	$colorTblName = COLORS_TBL;
}

$spaceSql = "st.intersects(st.transform(GIS_DATA_simple,4326), (st.geomfromtext('POLYGON(($minX $minY, $minX $maxY ,$maxX $maxY ,$maxX $minY ,$minX $minY))',4326))) = 1 ";

$sql = "select t.name1 as name, p.blockId as pending, t.oid as HQ_Id, t.point_string_simple  
	from $tableName t
	LEFT OUTER JOIN (SELECT DISTINCT blockId FROM ".PENDING_TBL.") as p
	ON t.oid=p.blockId
	where $spaceSql";
$points = $db->GetArray($sql);

$meta = array();	// additional info: color, name etc
$res = array();

foreach($points as &$r) {
        $r['point_string_simple'] = str_replace('(', '', $r['point_string_simple']);
        $r['point_string_simple'] = str_replace(')', '', $r['point_string_simple']);
        $r['point_string_simple'] = str_replace('POLYGON', '', $r['point_string_simple']);
        $r['point_string_simple'] = str_replace('MULTIPOLYGON', '', $r['point_string_simple']);

	$r['pending'] = $r['pending'] ? 1 : 0;

        $res[$r['HQ_Id']] = str_replace('"','',  $r['point_string_simple']);
	$meta[$r['HQ_Id']] = array('name' => $r['name'], 'pending' => $r['pending']);
	
}


$ret = array();
foreach($res as $key => $val) {
        $val = explode(',', $val);
                $ret[$key] = array();

        $j = 1; // ($zoomStr=='neighborhoods') ? 1 : 2;

        for($i=0; $i<count($val); $i+=$j) {
                $points = explode(' ', $val[$i]);
                $points = array_reverse($points);
                array_push($ret[$key], $points);
        }

        if($ret[$key][0]!=$ret[$key][-1])
                array_push($ret[$key], $ret[$key][0]);

}


$encoded = array();
foreach($ret as $key => $val) {
        $encoded[$key] = array('points' => dpEncode($val),
		'name' => $meta[$key]['name'],
		'pending' => $meta[$key]['pending']
	);
}


echo json_encode($encoded);
?>
